/*  File    : apwm.c
 *  Abstract:
 */

#define S_FUNCTION_NAME apwm
#define S_FUNCTION_LEVEL 2

#include "simstruc.h"

#define fs  mxGetPr(ssGetSFcnParam(S, 0))[0]

#define uaref   *uPtrs[0]
#define ubref   *uPtrs[1]
#define ucref   *uPtrs[2]
#define Udc     *uPtrs[3]

#define tswa      y[0]
#define tswb      y[1]
#define tswc      y[2]

/* Function: mdlInitializeSizes ===============================================
 * Abstract:
 *    The sizes information is used by Simulink to determine the S-function
 *    block's characteristics (number of inputs, outputs, states, etc.).
 */
static void mdlInitializeSizes(SimStruct *S) {
    ssSetNumSFcnParams(S, 1);  /* Number of expected parameters */
    if (ssGetNumSFcnParams(S) != ssGetSFcnParamsCount(S)) {
        return; /* Parameter mismatch will be reported by Simulink */
    }
    
    ssSetNumContStates(S, 0);
    ssSetNumDiscStates(S, 0);
    
    if (!ssSetNumInputPorts(S, 1)) return;
    ssSetInputPortWidth(S, 0, 4);
    ssSetInputPortDirectFeedThrough(S, 0, 1);
    
    if (!ssSetNumOutputPorts(S, 1)) return;
    ssSetOutputPortWidth(S, 0, 4);
    
    ssSetNumSampleTimes(S, 1);
    ssSetNumRWork(S, 0);
    ssSetNumIWork(S, 1);
    ssSetNumPWork(S, 0);
    ssSetNumModes(S, 0);
    ssSetNumNonsampledZCs(S, 0);
    ssSetSimStateCompliance(S, USE_DEFAULT_SIM_STATE);
    
    if (ssGetSimMode(S) == SS_SIMMODE_RTWGEN && !ssIsVariableStepSolver(S)) {
        ssSetErrorStatus(S, "S-function vsfunc.c cannot be used with RTW "
                "and Fixed-Step Solvers because it contains variable"
                " sample time");
    }
    
    /* Take care when specifying exception free code - see sfuntmpl_doc.c */
    ssSetOptions(S, SS_OPTION_EXCEPTION_FREE_CODE);
}

/* Function: mdlInitializeSampleTimes =========================================
 * Abstract:
 *    Variable-Step S-function
 */
static void mdlInitializeSampleTimes(SimStruct *S) {
    ssSetSampleTime(S, 0, VARIABLE_SAMPLE_TIME);
    ssSetOffsetTime(S, 0, 0.0);
    ssSetModelReferenceSampleTimeDefaultInheritance(S);
}

#define MDL_INITIALIZE_CONDITIONS
/* Function: mdlInitializeConditions ========================================
 * Abstract:
 */
static void mdlInitializeConditions(SimStruct *S) {
    ssSetIWorkValue(S, 0, -1);          //Carrier (up or down)
}

#define MDL_GET_TIME_OF_NEXT_VAR_HIT
static void mdlGetTimeOfNextVarHit(SimStruct *S) {
    ssSetTNext(S, ssGetT(S)+1/(2*fs));
}

/* Function: mdlOutputs =======================================================
 * Abstract:
 */
static void mdlOutputs(SimStruct *S, int_T tid) {
    InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S, 0);
    real_T *y = ssGetOutputPortSignal(S, 0);
    double  umax, umin, uopt;
    
    int carrier;    //Carrier (up or down)
    
    carrier = ssGetIWorkValue(S, 0);
    
    if (carrier < 1) {
        carrier = 1;
    }
    else if (carrier > 0) {
        carrier = -1;
    }
    
    //Summetrization
    if (uaref > ubref) {
        umax=uaref;
        umin=ubref;
    }
    else {
        umax=ubref;
        umin=uaref;
    }
    if (ucref > umax)
        umax=ucref;
    else if (ucref < umin)
        umin=ucref;
    
    uopt=0.5*(umax+umin);
    
    tswa=((uaref-uopt)+carrier*Udc/2)/(carrier*2*fs*Udc);
    tswb=((ubref-uopt)+carrier*Udc/2)/(carrier*2*fs*Udc);
    tswc=((ucref-uopt)+carrier*Udc/2)/(carrier*2*fs*Udc);
    
    if (tswa > 1/(2*fs)) {
        tswa=1/(2*fs);
    }
    else if (tswa < 0.0) {
        tswa=0.0;
    }
    if (tswb > 1/(2*fs)) {
        tswb=1/(2*fs);
    }
    else if (tswb < 0.0) {
        tswb=0.0;
    }
    if (tswc > 1/(2*fs)) {
        tswc=1/(2*fs);
    }
    else if (tswc < 0.0) {
        tswc=0.0;
    }
    
    //Output carrier flag
    y[3]=carrier;
    
    ssSetIWorkValue(S, 0, carrier);
}

#define MDL_UPDATE
/* Function: mdlUpdate ========================================================
 * Abstract:
 *    This function is called once for every major integration time step.
 *    Discrete states are typically updated here, but this function is useful
 *    for performing any tasks that should only take place once per integration
 *    step.
 */
static void mdlUpdate(SimStruct *S, int_T tid) {
}

/* Function: mdlTerminate =====================================================
 * Abstract:
 *    No termination needed, but we are required to have this routine.
 */
static void mdlTerminate(SimStruct *S) {
}

#ifdef  MATLAB_MEX_FILE    /* Is this file being compiled as a MEX-file? */
#include "simulink.c"      /* MEX-file interface mechanism */
#else
#include "cg_sfun.h"       /* Code generation registration function */
#endif